package com.lh.glorypavilion.service.sms.controller.api;

import com.aliyuncs.exceptions.ClientException;
import com.lh.glorypavilion.result.R;
import com.lh.glorypavilion.service.sms.service.SmsService;
import com.lh.glorypavilion.util.FormUtils;
import com.lh.glorypavilion.util.RandomUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

//@CrossOrigin
@Api(description = "短信发送")
@RestController
@RequestMapping("/api/sms")
@RefreshScope
@Slf4j
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("发送短信")
    @GetMapping("send/{mobile}")
    public R getCode(@ApiParam("手机号") @PathVariable("mobile") String mobile) throws ClientException {

        //1：校验手机号是否合法
        if(StringUtils.isEmpty(mobile)||!FormUtils.isMobile(mobile)){
            log.error("手机号不正确！");
            return R.error().message("手机号不正确！").code(28001);
        }

        //2：生成验证码
        String sixBitRandom = RandomUtils.getSixBitRandom();

        //3；发送验证码
        //smsService.send(mobile,sixBitRandom);
        log.info("验证码"+sixBitRandom);

        //4：存储验证码到Redis
        redisTemplate.opsForValue().set(mobile,sixBitRandom,5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功！");
    }

    @GetMapping("test")
    public R test(){
        return R.ok().message(signName);
    }

}
